<?php

/**
 * 天翼开放平台短信访问类
 *
 * @author flybug
 * @data 2014-06-05
 *
 */
class sms {

    private $sms_UserId;
    private $sms_KeyId;
    private $sms_Secret;
    private $sms_Type = 0; //短信发送平台：0-电信天翼；1-短信网
    private $sms_Error;
	
	/* 示远短信配置账号：
密码：
【大唐天下】 */
    private $syConfig = [
		'noSupport'	=> [11, 12, 13, 14, 15, 16, 18, 20, 22, 24, 25, 27],
		'support'	=> [1],
		'chanel1'	=> [//普通接口
			'api'		=> 'http://send.18sms.com/msg/HttpBatchSendSM',
			'account'	=>'q5gd78',
			'pswd'		=>'Gv573N0X'
		],	
		'chanel2'	=> [//营销接口
			'api'		=> 'http://121.43.107.8:8888',
			'userid'	=>12,
			'account'	=>'',
			'password'	=>''
		]
	];
	
	/* 焱阳短信配置 */
	private $yyConfig = [
		'sms_UserId'	=>	'519',
		'sms_KeyId'	=>	'hndt',
		'sms_Secret'	=>	'0E156917215fcA',
		'sms_Type'	=>	2,
	];
	
    //模版短信映射表
    private $sms_Map = array(
        'validate' => '91549108',
//        'order_success' => '91001958',
//        'order_fail' => '91001959',
//        'try_success' => '91001885',
//        'try_fail' => '91001896'
    );
    private $accessToken; //访问令牌
    private $accessToken_Url = 'https://oauth.api.189.cn/emp/oauth2/v3/access_token'; //访问令牌获取地址
    //private $redirect_AccessToken_Url = 'http://www.youpinshiyong.com/?model=sms&do=getAccessToken';//访问令牌回调地址
    private $token; //授权码
    private $send_token_Url = 'http://api.189.cn/v2/dm/randcode/token'; //获取授权码地址
    private $send_RandCode_Url = 'http://api.189.cn/v2/dm/randcode/send'; //发送验证码短信息地址
    private $redirect_RandCode_Url = 'http://user.youpinshiyong.com/?model=sms&do=getRundCode'; //获取短信验证码回调地址
    private $send_TemplateSms_Url = 'http://api.189.cn/v2/emp/templateSms/sendSms'; //发送模版短信地址
    private $accessTokenCacheSign = '88577eb486bb54c4322659f4ff85b7dc'; //访问令牌缓存标识[md5(flybug_accessTokenCacheSign)]
    private $send_TemplateSMS_DXWUrl = 'http://web.duanxinwang.cc/asmx/smsservice.aspx';
    private $send_TemplateSMS_QYXSUrl = 'http://39.108.150.216:8808/sms.aspx';
    private $backList = array( );//黑名单号码;
    private $whiteList = [];
	private $prefixSign = '';
	
    public function __construct() {

        $this->sms_UserId = $this->yyConfig['sms_UserId'];
        $this->sms_KeyId = $this->yyConfig['sms_KeyId'];
        $this->sms_Secret = $this->yyConfig['sms_Secret'];
        $this->sms_Type = $this->yyConfig['sms_Type'];
    }

    //获取Access_token，自动缓存
    /*
     * @param $clearCache 是否强制刷新token,默认不强制刷新
     */
    public function getAccessToken($type = 'client_credentials', $clearCache = 0) {
        $cache = new cache();
        $this->accessToken = $cache->get($this->accessTokenCacheSign);
        if ($clearCache || !$this->accessToken) {
            $param = array(
                'app_id' => $this->sms_KeyId,
                'app_secret' => $this->sms_Secret,
                'grant_type' => $type
            );
            $ret = json_decode(F::curl($this->accessToken_Url, $param), true);
            $this->accessToken = $ret['access_token'];
            $cache->set($this->accessTokenCacheSign, $this->accessToken, $ret['expires_in']); //缓存当前accesstoken
        }
    }

    //获取信任
    public function getToken() {
        $param['app_id'] = "app_id=" . $this->sms_KeyId;
        $param['access_token'] = "access_token=" . $this->accessToken;
        $param['timestamp'] = "timestamp=" . date('Y-m-d H:i:s');
        ksort($param);
        $plaintext = implode("&", $param);
        $param['sign'] = "sign=" . rawurlencode(base64_encode(hash_hmac("sha1", $plaintext, $this->sms_Secret, $raw_output = True)));
        $result = F::curl($this->send_token_Url . '?' . $plaintext . '&' . $param['sign']);
        $resultArray = json_decode($result, true);
        $this->token = $resultArray['token'];
    }

    //发送模版短信
    private function SendTemplateSMS($phone, $tid, $tparam) {
		if(!F::regularCheck('mobile', $phone)){
			$this->sms_Error = -99;
			return false;
		}
        //return true;
        switch ($this->sms_Type) {
            case 2://企业信使
                switch($tparam['tempId']){
                    case 1:
						$content = '你启动的财务下载任务已经完成，请及时下载。';
						break;
                    default:
                        $this->sms_Error = -6;
                        return false;
                        break;
                }

                $param = array(
                    'userid' => $this->sms_UserId,
                    'account' => $this->sms_KeyId,
                    'password' => $this->sms_Secret,
                    'content' => $content,
                    'mobile' => $phone,
                    'sendTime' => '',
                    'action' => 'send',
                    'extno' => ''
                );

				if(substr($phone,0,3) == '144'){    //145开头的号码为测试账号
                    return true;
                }else{
                    $result = xml::xml2array(F::curl($this->send_TemplateSMS_QYXSUrl, $param));

                    if($this->sySmsSend($param)){//示远发送成功							
                        return true;
                    }
                }
                break;
        }
    }

    //发送模版认证短信（成功返回验证码索引id，失败返回0）
    public function SendValidateSMS($phone,$tempId = 1,$data = array(), $nick = '大唐天下') {
        if (!F::isPhone($phone)) {
            $this->sms_Error = -3;//不是有效的手机号码
            return false;
        }

        //防止频繁发送，间隔需要120秒(放在cache里)
        $p = array(
            'nick' => $nick,
            'code' => $code,
            'tempId' => $tempId
        );

        $p = array_merge($p,$data);

        if ($this->SendTemplateSMS($phone, $this->sms_Map['validate'], $p)) {
            if($tempId == 2){
                return $code;
            }else{
                return true;
            }
        } else {
            if(!$this->sms_Error){
                $this->sms_Error = -1;
            }
            return false;
        }
    }
	
	private function sySmsSend($param){
		$post_data = array();
		$syConfig = $this->syConfig['chanel1'];
		$post_data['account']	 = $syConfig['account'];   //帐号
		$post_data['pswd']		 = $syConfig['pswd'];  //密码
		$post_data['msg']		 = urlencode($param['content']); //短信内容需要用urlencode编码下
		$post_data['mobile']	 = $param['mobile']; //手机号码， 多个用英文状态下的 , 隔开
		$post_data['product']	 = ''; //产品ID
		$post_data['needstatus'] = true; //是否需要状态报告，需要true，不需要false
		$post_data['extno']		 = '';  //扩展码   可以不用填写
		$url					 = $syConfig['api'];
		
		$result	= F::curl($url, $post_data);
		$resArr = explode(',', $result);
		if(count($resArr) == 2){
			if($resArr[1] == '0'){
				return true;
			}
			else{				
				$this->sms_Error = '发送失败sy:'.$result.'_'.$post_data.'_'.json_encode($syConfig);//发送失败
				return false;
			}
		}
		else{
			$this->sms_Error = '发送失败sy';//发送失败
			return false;
		}
	}

    //测试短信发送
    public function test($phone) {
        return $this->SendValidateSMS($phone);
    }

    //短信发送失败的原因
    public function getError() {
        return $this->sms_Error;
    }

}

?>
